package com.intel.factorytest.activity;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.BatteryManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.intel.factorytest.R;

public class BatteryStatusCheck extends Activity implements android.view.View.OnClickListener
{

    private TextView mTextView;
    private Button mButton;
    private static final String TEST_ITEM = "test_item";
    private static final String TAG = "battery_status";
    private static final String voltage_path = "/sys/class/power_supply/max17047_battery/uevent";
    private static final String VOLTAGE_DIRECTORY = "/sys/class/power_supply/";

    int scale = 0;
    int plugType = 0;
    int status = 0;
    int health = 0;
    int temperature = 0; 
      private static final String TEST_ITEM_RESULT = "test_item_result";
     boolean is_pass = false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        Intent intent = getIntent();
        String orientationStr = intent.getStringExtra("sd_orientation");
        int orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
        Log.i("util","orientationStr = " + orientationStr);
        if(orientationStr.equals("SCREEN_ORIENTATION_PORTRAIT")) {
            orientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
            super.setRequestedOrientation(orientation);

        } else if(orientationStr.equals("SCREEN_ORIENTATION_LANDSCAPE")) {
            orientation = ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
            super.setRequestedOrientation(orientation);

        }
            setContentView(R.layout.battery_status);
        mTextView = (TextView)findViewById(R.id.battery_status_txt);
        mButton = (Button)findViewById(R.id.battery_status_btn);

        mButton.setOnClickListener(this);

    }

    @Override
    protected void onResume() {
        IntentFilter mIntentFilter = new IntentFilter();
        mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(mBatteryInfoReceiver, mIntentFilter, "permission.CIT_ALLOW_BROADCAST", null);
        super.onResume();
    }
    
    private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver(){
    
            @Override
            public void onReceive(Context context, Intent intent) {
                // TODO Auto-generated method stub
            
                String action = intent.getAction();
            
                if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
                
                    scale = intent.getIntExtra("voltage", 0);

                    plugType = intent.getIntExtra("plugged", 0);
                    status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
                    health = intent.getIntExtra("health", BatteryManager.BATTERY_HEALTH_UNKNOWN);
                    temperature = intent.getIntExtra("temperature", BatteryManager.BATTERY_HEALTH_UNKNOWN);
                    setSummary(scale, plugType, status, health, temperature);
                }
        
            }
        
        };
    
    private String getlevel() 
        {
            String tempStr = "Unavailable";
            int pos = 0;
            int value = 0;
            Log.i(TAG, "pos = " + pos);
            String target = "POWER_SUPPLY_VOLTAGE_NOW=";
            try {
                File voltageFile = new File(voltage_path);
                if(voltageFile.exists()) {
                    BufferedReader reader = new BufferedReader(new FileReader(voltage_path));
                    try {
                        do {
                            tempStr = reader.readLine();
                            Log.i(TAG, "tempStr: " + tempStr);
                            pos = tempStr.indexOf(target);
                            Log.i(TAG, "pos = " + pos);
                        }while(pos != 0 && tempStr != null);
                        pos = pos + target.length();
                        tempStr = tempStr.substring(pos, pos + 4);
                    } finally {
                        reader.close();
                    }
                } else {
                    File directory = new File(VOLTAGE_DIRECTORY);
                    File[] files = directory.listFiles();
                    for(File file : files) {
                        Log.i(TAG, "file = " + file.getName());
                        if(file.getName().contains("battery")) {
                            String tmpDir = VOLTAGE_DIRECTORY + file.getName();
                            directory = new File(tmpDir);
                            files = directory.listFiles();
                            for(File subFile : files) {Log.i(TAG, "subfile = " + subFile.getName());
                                if(subFile.getName().equals("uevent")) {Log.i(TAG, "subfile2 = " + tmpDir + "/" + "uevent");
                                    BufferedReader reader = new BufferedReader(new FileReader(tmpDir + "/" + "uevent"));
                                    try {
                                        do {
                                            tempStr = reader.readLine();
                                            Log.i(TAG, "tempStr: " + tempStr);
                                            pos = tempStr.indexOf(target);
                                            Log.i(TAG, "pos = " + pos);
                                        }while(pos != 0 && tempStr != null);
                                        pos = pos + target.length();
                                        tempStr = tempStr.substring(pos, pos + 4);
                                    } finally {
                                        reader.close();
                                    }
                                    break;
                                }
                            }
                            break;
                        }
                    }
                }
                return tempStr;
            } catch (IOException e) {  
                return "Unavailable";
            }
        }
    
    
    private void setSummary(int batteryV, int plugType, int status, int health, int temperature){
        String statusString;
        String healthString;
        if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
                    statusString = this.getString(R.string.SERVICEMENU_BATTERY_STATUS_CHARGING_TXT);
                    if (plugType > 0) {
                            statusString = statusString + " " + this.getString(
                            (plugType == BatteryManager.BATTERY_PLUGGED_AC)
                            ? R.string.SERVICEMENU_BATTERY_STATUS_CHARGING_AC_TXTB
                            : R.string.SERVICEMENU_BATTERY_STATUS_CHARGING_USB_TXT);
                is_pass = true;
                    }
            } else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
                    statusString = this.getString(R.string.SERVICEMENU_BATTERY_STATUS_DISCHARGING_TXT);
            } else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
                    statusString = this.getString(R.string.SERVICEMENU_BATTERY_STATUS_NOT_CHARGING_TXT);
            } else if (status == BatteryManager.BATTERY_STATUS_FULL) {
                    statusString = this.getString(R.string.SERVICEMENU_BATTERY_STATUS_FULL_TXT);
            is_pass = true;
            } else {
                    statusString = this.getString(R.string.SERVICEMENU_BATTERY_STATUS_UNKNOWN_TXT);
                }
        
        if (health == BatteryManager.BATTERY_HEALTH_GOOD) {
                    healthString = this.getString(R.string.SERVICEMENU_BATTERY_HEALTH_GOOD_TXT);
            } else if (health == BatteryManager.BATTERY_HEALTH_OVERHEAT) {
                    healthString = this.getString(R.string.SERVICEMENU_BATTERY_HEALTH_OVERHEAT_TXT);
            } else if (health == BatteryManager.BATTERY_HEALTH_DEAD) {
                    healthString = this.getString(R.string.SERVICEMENU_BATTERY_HEALTH_DEAD_TXT);
            } else if (health == BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE) {
                    healthString = this.getString(R.string.SERVICEMENU_BATTERY_HEALTH__OVER_VOLTAGE_TXT);
            } else if (health == BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE) {
                    healthString = this.getString(R.string.SERVICEMENU_BATTERY_HEALTH_UNSPECIFIED_FAILURE_TXT);
            } else {
                    healthString = this.getString(R.string.SERVICEMENU_BATTERY_HEALTH_UNKNOWN_TXT);
            }
        StringBuilder mStringBuilder = new StringBuilder();
        mStringBuilder.append(getString(R.string.SERVICEMENU_BATTERY_VOLTAGE_TXT));
        mStringBuilder.append(batteryV);
        mStringBuilder.append("mV");
        mStringBuilder.append("\n");
        mStringBuilder.append(getString(R.string.SERVICEMENU_BATTERY_STATUS_TXT));
        mStringBuilder.append(statusString);
        mStringBuilder.append("\n");
        mStringBuilder.append(getString(R.string.SERVICEMENU_BATTERY_HEALTH_TXT));
        mStringBuilder.append(healthString);
        mStringBuilder.append("\n");
        mStringBuilder.append(getString(R.string.SERVICEMENU_BATTERY_TEMPERATURE_TXT));
        float convertedTemperature = (float)temperature / 10.0f;
        mStringBuilder.append(convertedTemperature);
        mStringBuilder.append(getString(R.string.SERVICEMENU_BATTERY_TEMPERATURE_UNIT_TXT));
        mStringBuilder.append("\n");
        if(is_pass) {
            mStringBuilder.append(getString(R.string.SERVICEMENU_BATTERY_TEMPERATURE_OK_TXT) + "\n");
        }
        mTextView.setText(mStringBuilder.toString());
    }

    public void onClick(View v) {
        String tmp_voltage;
        switch (v.getId()) {
        case R.id.battery_status_btn:
            tmp_voltage = getlevel();
            if("Unavailable" != tmp_voltage) {
                scale = Integer.parseInt(tmp_voltage);
                setSummary(scale, plugType, status, health, temperature);
            }
            break;
        }
    }

    private void setTestResult () {
        Intent intent = new Intent();
        Intent mIntent = getIntent();
        int pos = mIntent.getIntExtra(TEST_ITEM,-1);
        intent.putExtra(TEST_ITEM,pos);
        intent.putExtra(TEST_ITEM_RESULT,is_pass);
//        Log.e(TAG,"pos ="+pos);
        setResult(0, intent);
    }
    @Override
    public void finish() {
        setTestResult (); 
        unregisterReceiver(mBatteryInfoReceiver);
        super.finish();
    }
}
